<template>
  <div>
    <div class="operation-bar">
      <el-button type="primary" size="small" @click="handleAdd">新增评价</el-button>
      <el-button type="primary" size="small" @click="refreshList">刷新</el-button>
    </div>

    <el-table v-loading="loading" :data="evaluationList" style="width: 100%; margin-top: 10px;">
      <el-table-column prop="evaluationId" label="ID" align="center"/>
      <el-table-column prop="evaluationPeriod" label="评价周期" align="center"/>
      <el-table-column label="评分详情" align="center" width="600">
        <template #default="scope">
          <div class="score-container">
            <div class="score-item">
              <span class="score-label">质量:</span>
              <el-rate
                v-model="scope.row.qualityScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                :max="10"
                :allow-half="true"
                :colors="rateColors"
              />
            </div>
            <div class="score-item">
              <span class="score-label">交付:</span>
              <el-rate
                v-model="scope.row.deliveryScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                :max="10"
                :allow-half="true"
                :colors="rateColors"
              />
            </div>
            <div class="score-item">
              <span class="score-label">价格:</span>
              <el-rate
                v-model="scope.row.priceScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                :max="10"
                :allow-half="true"
                :colors="rateColors"
              />
            </div>
            <div class="score-item">
              <span class="score-label">服务:</span>
              <el-rate
                v-model="scope.row.serviceScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                :max="10"
                :allow-half="true"
                :colors="rateColors"
              />
            </div>
            <div class="score-item">
              <span class="score-label">综合:</span>
              <el-rate
                v-model="scope.row.totalScore"
                disabled
                show-score
                text-color="#008000"
                score-template="{value}"
                :max="10"
                :allow-half="true"
                :colors="rateColors"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="evaluator" label="评价人" align="center"/>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="text" size="small" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 评价表单对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" :before-close="handleClose">
      <evaluation-form
          ref="evaluationForm"
          :supplier-id="supplierId"
          :evaluation="currentEvaluation"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" v-if="!isViewMode">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEvaluationsBySupplierId,
  getEvaluation,
  addEvaluation,
  updateEvaluation,
  deleteEvaluation
} from '@/api/supplierEvaluation';
import EvaluationForm from './EvaluationForm.vue';

export default {
  name: 'EvaluationList',
  components: {
    EvaluationForm
  },
  props: {
    supplierId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      evaluationList: [],
      dialogVisible: false,
      dialogTitle: '',
      currentEvaluation: {},
      isViewMode: false,
      // 评分颜色配置：低分红色、中分黄色、高分绿色
      rateColors: ['#F56C6C', '#E6A23C', '#67C23A'],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取评价列表
    getList() {
      if (!this.supplierId) return;

      this.loading = true;
      getEvaluationsBySupplierId(this.supplierId).then(res => {
        if (res.code === 200) {
          this.evaluationList = res.data || [];
        } else {
          this.$message.error('获取评价记录失败');
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 刷新列表
    refreshList() {
      this.getList();
    },

    // 新增评价
    handleAdd() {
      this.dialogTitle = '新增评价';
      this.currentEvaluation = {};
      this.isViewMode = false;
      this.dialogVisible = true;
      if (this.$refs.evaluationForm) {
        this.$refs.evaluationForm.resetForm();
      }
    },

    // 编辑评价
    handleEdit(row) {
      this.dialogTitle = '编辑评价';
      this.isViewMode = false;

      getEvaluation(row.evaluationId).then(res => {
        if (res.code === 200) {
          this.currentEvaluation = res.data;
          this.dialogVisible = true;
        } else {
          this.$message.error('获取评价详情失败');
        }
      });
    },

    // 查看评价详情
    handleDetail(row) {
      this.dialogTitle = '评价详情';
      this.isViewMode = true;

      getEvaluation(row.evaluationId).then(res => {
        if (res.code === 200) {
          this.currentEvaluation = res.data;
          this.dialogVisible = true;
        } else {
          this.$message.error('获取评价详情失败');
        }
      });
    },

    // 删除评价
    handleDelete(row) {
      this.$confirm('确认删除该评价记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteEvaluation(row.evaluationId).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getList();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        });
      }).catch(() => {
      });
    },

    // 提交表单
    submitForm() {
      this.$refs.evaluationForm.validate().then(formData => {
        if (formData.evaluationId) {
          // 更新
          updateEvaluation(formData).then(res => {
            if (res.code === 200) {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.getList();
            } else {
              this.$message.error(res.message || '更新失败');
            }
          });
        } else {
          // 新增
          addEvaluation(formData).then(res => {
            if (res.code === 200) {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.getList();
              //调用父组件的方法并传参getSupplierDetail(formData.supplierId);

            } else {
              this.$message.error(res.message || '添加失败');
            }
          });
        }
      }).catch(err => {
        console.error('表单验证失败', err);
      });
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false;
    }
  }
}
</script>

<style scoped>
.operation-bar {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-start;
}

.delete-btn {
  color: #F56C6C;
}

.score-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  margin: 0 auto;
  width: fit-content;
}

.score-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  min-width: 350px;
  justify-content: center;
}

.score-label {
  font-weight: bold;
  width: 45px;
  text-align: right;
  margin-right: 12px;
  color: #606266;
}

/* 调整 el-rate 组件样式 */
:deep(.el-rate) {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

:deep(.el-rate__item) {
  margin-right: 4px !important;
}

:deep(.el-rate__text) {
  margin-left: 8px;
  min-width: 35px;
}
</style>
